<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="header-header">
          <img :src="imgUrl" alt="" style=" width: 100%;">
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{ formtype?'返回登录':'无账号，点击注册' }}</el-link>
      </div>
      <el-form
       ref="loginFormRef"
       :model="loginForm"
       style="max-width: 600px;"
       class="demo-ruleForm"
       :rules="rules"
       >
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" placeholder="手机号" :prefix-icon="User">
          </el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input v-model="loginForm.passWord" type="password"  placeholder="密码" :prefix-icon="Lock">
          </el-input>
        </el-form-item>
      <el-form-item v-if="formtype" prop="validCode">
          <el-input v-model="loginForm.validCode" placeholder="验证码" :prefix-icon="Lock"><template #append>
              <div>
                <span @click="countdownChange">{{ countdown.validText }}</span>
              </div>
            </template></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :style="{width: '100%'}" @click="sumbitForm(loginFormRef)">
          {{ formtype?'注册账号':'登录' }}
        </el-button>
      </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { reactive, ref,computed,toRaw } from 'vue';
//导入接口
import { getCode, userAuthentication,login} from '../../api/login';
import {menuPermissions} from '../../api/auth'
import {useMenuStore} from '../../stores/menuStore'
import {User,Lock} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import Storage from '../../local'

//pinia状态管理
const menuStore = useMenuStore() 
//引入路由
const router = useRouter()

const imgUrl= new URL('../../../public/logo.png',import.meta.url).href

 //点击切换登录和注册
 const handleChange = ()=>{
  formtype.value = formtype.value ? 0:1
 }

//表单数据
  const loginForm= reactive({
    userName:'',
    passWord:'',
    validCode:''
 })

 //切换表单数据,0登录，1注册
 const formtype = ref(0)

 //在输入时候账号校验
 const validateUser = (rule,value,callback)=>{
  if(value === ''){
    callback(new Error('请输入手机号'))
  } else{
    //用正则表达式进行校验
     const phoneReg =  /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
     phoneReg.test(value) ? callback():callback(new Error('手机号格式错误'))
  }
 }

 //密码校验
 const validatePassword = (rule,value,callback)=>{
  if(value === ''){
    callback(new Error('请输入密码'))
  } else{
     const passReg =  /^[a-zA-Z0-9_-]{4,16}$/
     passReg.test(value) ? callback():callback(new Error('请输入正确密码'))
  }
 }
  //表单校验，element进行校验
const rules = reactive({
  userName:[{validator:validateUser,trigger:'blur'}],
  passWord:[{validator:validatePassword,trigger:'blur'}]
})

 //发送短信
const countdown= reactive({
  validText:'获取验证码',
  time:60
 })

//防止冒泡
 let flag = false
 //倒计时实现
 const countdownChange = ()=>{
  if(flag) return
  const phoneReg =  /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if(!loginForm.userName || !phoneReg.test(loginForm.userName)){
     return ElMessage({
        message: '手机号错误',
        type: 'warning',
  })
  }
  //倒计时
  const time =  setInterval(() => {
    //如果flag存在 
    if(countdown.time<=0){
      countdown.time=60
      countdown.validText = `获取验证码`
      flag = false
      clearInterval(time)
    }
    countdown.time-=1
    countdown.validText = `剩余${countdown.time}s`
  }, 1000);

  flag=true
  //调用获取验证码接口
  getCode({
    tel:loginForm.userName
  }).then(({data})=>{
    if(data.code===10000){
      ElMessage({
        message: '验证码发送成功，请注意查收',
        type: 'success',
  })
    }
  })
 }
 //表单提交
 const loginFormRef=ref()

const routerList=computed(()=>menuStore.routerList)

 const sumbitForm =async (formEl)=>{
  
  if (!formEl) return
  
  //触发校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      //如果是注册页面
      if(formtype.value){
        // console.log(loginForm,'loginform');
        userAuthentication(loginForm).then(({data})=>{
          if(data.code===10000){
            ElMessage.success('注册成功')
            formtype.value=0
        }
        })
      }else{
        //登录页面
         login(loginForm).then(({data})=>{
          if(data.code===10000){
          ElMessage.success('登录成功')
          //将token缓存到浏览器
          localStorage.setItem('ak_token',data.data.token)
          //运用二次封装的local
          Storage.setItem('userInfo',JSON.stringify(data.data.userInfo))
          menuPermissions().then(({data})=>{
            menuStore.dynamicMenu(data.data)
            //toRaw获取该响应式对象的原始值,添加动态路由
            toRaw(routerList.value).forEach(item => {
              router.addRoute('main',item)
            });
            // const currentRoutes = router.getRoutes();
            // console.log('动态添加完之后路由情况:', currentRoutes)

             // 异步操作，等数据缓存之后在进行跳转
             new Promise((resolve) => {
                 resolve();
             }).then(() => {
                router.push('/');
             })
          })
          
          }
        })
      }
    } else {
      ElMessage.error('失败')
    }
  })
 }
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }

</style>